//app.js
const loginService = require("service/login.service.js");
App({
  onLaunch: function () {
  },
  wxInit: function (options) {
    var app = options.app;
    var url = options.url;
    wx.checkSession({
      success: res => {
        console.log("微信session有效")
        // 有效
        // 恢复storage中的数据到globalData中
        loginService.restoreCookie({ app: app });
        loginService.restoreUser({ app: app });
        // 验证后台Session是否有效
        loginService.sessionCheck({
          app: app,
          invalid: res => {
            // 无效
            console.log('后台session失效');
            // 清理本地存储
            loginService.clearCookie({ app: app });
            loginService.clearUser({ app: app });
            // 登录
            app.wxLogin(options);
          },
          valid: res => {
            // 有效
            console.log('后台session有效');
            wx.hideLoading();
            if (url != '/pages/mine/mine') {
              wx.navigateTo({
                url: url,
              });
            } else {
              options.reload();
            }
          }
        });
      },
      fail: res => {
        // 无效
        console.log("微信session无效")
        loginService.clearCookie({ app: app });
        loginService.clearUser({ app: app });
        // 登录
        console.log("开始登陆");
        app.wxLogin(options);
      }
    });
  },
  wxLogin: options => {
    var app = options.app;
    var url = options.url;
    wx.login({
      success: res => {
        var code = res.code;
        console.log("微信登录成功，Code：", code);
        loginService.login({
          app: app,
          code: code,
          success: res => {
            console.log(app.globalData);
            console.log(url);
            if (url != '/pages/mine/mine') {
              wx.navigateTo({
                url: url,
              });
            } else {
              options.reload();
            }

            wx.hideLoading();
          }
        });
      },
      fail: res => {
        wx.showToast({
          title: '微信登录失败！',
          icon: 'none',
          mask: true
        });
      }
    });
  },
  globalData: {
    requestHeader: {},
    userInfo: null,
    user: null,
    apiServerUrl: "http://192.168.31.106:8085"
  }
})